//
//  XWAccountDataManager.swift
//  XiaoweHealthy
//
//  Created by Riven on 2022/4/9.
//

import Foundation
import DMRCommonBaseLib


// MARK: - 用户数据管理
class XWAccountDataManager {
    
    static let shared: XWAccountDataManager = XWAccountDataManager()
    
    private var defaults: Defaults {
        Defaults.shared
    }
    
    private let kCurrentToken = Key<String>("currentToken")
    private let kCurrentUser = Key<String>("currentUser")
    
    var isUserLogined: Bool  {
        guard let token = getCurrentToken(), !token.isEmpty else {
            return false
        }
        
        return true
    }
    
    private init() {
        
    }
    
    func getCurrentToken() -> String? {
        defaults.get(for: kCurrentToken)
    }
    
    func setCurrentToken(_ token: String?) {
        guard let tToken = token else {
            defaults.clear(kCurrentToken)
            return
        }
        
        defaults.set(tToken, for: kCurrentToken)
    }
    
    func getCurrentUser() -> XWUserModel? {
        guard let tJson = defaults.get(for: kCurrentUser) else {
            return nil
        }
        
        guard let tUserModel = XWUserModel.deserialize(from: tJson) else {
            log.error("解析当前用户失败 \n")
            return nil
        }
        
        return tUserModel
    }
    
    func setCurrentUser(_ userModel: XWUserModel?) {
        guard let tUserModel = userModel else {
            log.info("删除当前用户 \n")
            AppInnerNotificationManager.postAccountLoginNotification(isLogined: false)
            defaults.clear(kCurrentUser)
            return
        }
        
        guard let tJson = tUserModel.toJSONString() else {
            log.error("保存当前用户信息失败 \n")
            AppInnerNotificationManager.postAccountLoginNotification(isLogined: false)
            defaults.clear(kCurrentUser)
            return
        }
        
        log.info("保存当前用户信息 userInfo = \(tUserModel) \n")
        AppInnerNotificationManager.postAccountLoginNotification(isLogined: true)
        defaults.set(tJson, for: kCurrentUser)
    }
    
    func cleanLoginInfo() {
        setCurrentToken(nil)
        setCurrentUser(nil)
    }
    
}
